#!/bin/gawk -f
# qguessc: Script to guess coordinate file type (i.e. program type).
# Exit code: the file type number, or 0 on error (!)
# =============================================================
# Ton Rullmann, August 20, 1996
# =============================================================
# File type 1 = PDB  ( HB1/2 )
#           2 = PDBN ( HB2/3, H5''/'H5' )
#           3 = BIOSYM
#           4 = PDB XPLOR style ( HB1/2 inverted ) (not detected here)
#           5 = PDB MOLMOL style                   (not detected here)
#          99 = user defined (not used; changed to 0 at end)

BEGIN {
    if ( ARGC <= 1 ) {
	print "usage: qguessc file"
	exit ( 1 )
    }
    filtyp_fnd = 0
    filtyp_unk = 99
    checkd = 0
    pdbnew = 0
}

function error() {
    filtyp_fnd = 0
    exit
}

function checkft( num ) {
    if ( filtyp_fnd == filtyp_unk ) return
    if ( !filtyp_fnd )
	filtyp_fnd = num
    else {
	if ( filtyp_fnd != num ) {
	    print "* Inconsistent file type. Previously found type", filtyp_fnd, "now", num
	    print "* At line:", org 
	    if ( fatal ) 
		error()
	    else
		filtyp_fnd = filtyp_unk
	}
    }
    checkd = 1
}

# start processing - first change to uppercase

    {
    $0 = toupper( $0 )
}

# PDB type

$1 == "ATOM" || $1 == "HETATM"  { 
    checkft( 1 )
    if ( ( $3 == "HB3"  || $3 == "3HB" ) && $4 !~ /ALA/ ) pdbnew = 1
    if ( ( $3 == "H5''" || $3 == "'H5'" ) ) pdbnew = 1
    next
}

# BIOSYM type

/^!BIOSYM *ARCHIVE/ {
    checkft( 3 )
# end after finding one line
    exit
}

$1 == "TER" || $1 ~ /^END/ {
    exit
}

END {
    if ( filtyp_fnd == 0 ) {
	if ( checkd )
	    print "* Coordinate file type could not be determined due to error(s)"
	else
	    filtyp_fnd = filtyp_unk
    }
    if ( filtyp_fnd == filtyp_unk ) {
	print "* Coordinate file type UNKNOWN"
	filtyp_fnd = 0
    }
    if ( filtyp_fnd == 1 ) {
	if ( ! pdbnew )
	    print "* Coordinate file type determined as PDB"
	else {
	    print "* Coordinate file type determined as PDBN"
	    filtyp_fnd = 2
	}
    }
    if ( filtyp_fnd == 3 ) print "* Coordinate file type determined as BIOSYM"
    exit( filtyp_fnd )
}
